<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>节点操作（增删改）</title>
  <link href="src/css/layui.css" rel="stylesheet">
  <link href="examples/layui-icon-additional/iconfont.css" rel="stylesheet">
  <style>
  </style>
</head>
<body>
<div class="layui-fluid" style="padding: 15px;">
  <table id="demo"></table>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="addChild">新增子节点</a>
  <a class="layui-btn layui-btn-xs" lay-event="more">更多 <i class="layui-icon layui-icon-down"></i></a>
</script>

<script src="src/layui.js"></script>
<script src="examples/js/mock.js"></script>
<script>
  layui.use(['treeTable', 'dropdown'], function () {
    var treeTable = layui.treeTable;
    var dropdown = layui.dropdown;

    treeTable.set({
      tree: {
        view: {
          iconOpen: '<i class="layui-icon layui-icon-folderOpen"></i>',
          iconClose: '<i class="layui-icon layui-icon-folder2"></i>',
          iconLeaf: '<i class="layui-icon layui-icon-file"></i>', // 设置默认的叶子菜单图标
          // iconLeaf: '<i class="layui-icon layui-icon-leaf"></i>', // 设置默认的叶子菜单图标
        }
      },
    })

    // 生成随机ID函数
    const createId = (() => {
      let nextId = 1
      return () => nextId++
    })()

    // 生成节点函数
    const createNode = (parentId = null, level = 0) => {
      const id = createId()
      const children = level < 3 ? Mock.mock({
        'array|0-5': [
          createNode.bind(null, id, level + 1)
        ]
      }).array : []

      return {
        id,
        name: `User${id}`,
        type: Mock.mock('@d6'),
        status: Mock.Random.d4(),
        score: Mock.Random.d100(),
        experience: Mock.Random.integer(1000, 99999),
        sex: Mock.Random.cword('男女', 1),
        city: Mock.Random.city(),
        description: Mock.mock('@cparagraph'),
        createTime: Mock.mock('@datetime'),
        parentId,
        children,
        isParent: !!children.length
      }
    }

    // 生成树
    const rootNodes = Mock.mock({
      'array|10-20': [
        createNode
      ]
    }).array

    // 将树展开
    const flattenTree = (nodes, parentId = null) => {
      let result = []
      nodes.forEach(node => {
        result.push({
          ...node,
          parentId,
          children: undefined
        })
        if (node.children.length > 0) {
          result = result.concat(flattenTree(node.children, node.id))
        }
      })
      return result
    }

    const getTreeData = function (nodes) {
      let result = []
      nodes.forEach(node => {
        result.push({...node, parentId: null, children: getTreeData(node.children)});
      })
      return result
    }

    var testDatas = flattenTree(rootNodes);
    // var testDatas = getTreeData(rootNodes);

    treeTable.render({
      elem: '#demo',
      data: testDatas,
      // url: '/getDatas',
      totalRow: true,
      toolbar: '<div><span class="layui-btn layui-btn-sm" lay-event="addNode">新增根节点</span></div>',
      tree: {
        view: {
          // iconLeaf: '<img src="https://img1.baidu.com/it/u=3001670317,1989854300&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" alt="">' // 可以自定义图标
        },
        data: {
          simpleData: {
            enable: true // 异步加载子节点的一般返回的就是当前父节点的子节点不会带跨层级的节点信息
          }
        },
        async: {
          // enable: true,
          // autoParam: ['parentId=id']
        },
      },
      page: true,
      maxHeight: 'full-30',
      cols: [[
        {type: 'numbers', fixed: 'left'}
        , {field: 'id', title: 'ID', width: 145, sort: true, fixed: 'left', totalRow: '合计：'}
        , {field: 'name', title: '用户名', width: 180, fixed: 'left', edit: true}
        , {field: 'experience', title: '积分', width: 90, sort: true, edit: true,totalRow: '{{= d.TOTAL_NUMS }}'}
        , {field: 'sex', title: '性别', width: 80, sort: true}
        , {field: 'score', title: '评分', width: 80, sort: true, totalRow: true}
        , {field: 'city', title: '城市', width: 150, templet: '#tpl1'}
        , {field: 'description', title: '描述信息', minWidth: 200, templet: '#tpl2'}
        , {field: 'createTime', title: '创建时间', width: 170}
        , {fixed: 'right', title: '操作', width: 226, align: 'center', toolbar: '#barDemo'}
      ]],
      done: function (res, curr, count) {
        // console.log('渲染完成', res, curr, count);
      }
    });

    // 单元格工具事件
    treeTable.on('tool(demo)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var layEvent = obj.event; //获得 lay-event 对应的值
      var trElem = obj.tr;
      var trData = obj.data;
      var tableId = obj.config.id;

      if (layEvent === 'detail') {
        layer.msg('查看操作：' + trData.name);
      } else if (layEvent === 'addChild') {
        var newNode = {id: Date.now(), name: '新增节点'};
        var newNode2 = treeTable.addNodes(tableId, trData['LAY_DATA_INDEX'], -1, newNode);
      } else if (layEvent === 'more') {
        //下拉菜单
        dropdown.render({
          elem: this //触发事件的 DOM 对象
          , show: true //外部事件触发即显示
          , data: [{
            title: '修改积分'
            , id: 'edit'
          }, {
            title: '删除'
            , id: 'del'
          }]
          , click: function (menudata) {
            if (menudata.id === 'del') {
              layer.confirm('真的删除行么', function (index) {
                obj.del();
                // treeTable.del(tableId, trElem.attr('data-index'));
                layer.close(index);
              });
            } else if (menudata.id === 'edit') {
              layer.prompt({
                value: trData.experience,
                title: '输入新的积分'
              }, function (value, index) {
                obj.update({experience: value}); // 等效如下
                // treeTable.updateNode(tableId, trElem.attr('data-index'), {experience: value});
                layer.close(index);
              })
            }
          }
          , align: 'right' //右对齐弹出
        })
      }
    });

    // 表头工具栏工具事件
    treeTable.on('toolbar(demo)', function (obj) {
      var config = obj.config;
      var tableId = config.id;
      if (obj.event === 'addNode') {
        treeTable.addNodes(tableId, null, -1, {id: Date.now(), name: '新增节点', isParent: true});
      }
    })
  })
</script>
</body>
</html>
